package com.moco.launcher.activity;

import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import u.aly.da;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.moco.launcher.LauncherApplication;
import com.moco.launcher.R;
import com.moco.launcher.adapter.DataAdapter;
import com.moco.launcher.adapter.MainFlagmentAdapter;
import com.moco.launcher.alarm.AlarmReceiver;
import com.moco.launcher.bean.MOCO_CONSTANTS;
import com.moco.launcher.bean.MocoItemInfo;
import com.moco.launcher.fragment.MusicCategoryFragment;
import com.moco.launcher.fragment.PlayFragment;
import com.moco.launcher.fragment.SettingFragment;
import com.moco.launcher.link.LinkManager;
import com.moco.launcher.listener.FragmentChangeListener;
import com.moco.launcher.listener.OnMusicCategorySelectedListener;
import com.moco.launcher.listener.OnStorySelectedListener;
import com.moco.launcher.listener.PlayCallback;
import com.moco.launcher.listener.VoicePlayListener;
import com.moco.launcher.play.MocoPlayerClient;
import com.moco.launcher.play.MusicItemInfo;
import com.moco.launcher.play.OnStatusChangeCallback;
import com.oazon.common.util.LightnessControl;
import com.oazon.common.util.RequestManager;
import com.oazon.common.util.StringUtils;
import com.moco.launcher.view.DrawView;
import com.oazon.common.Assert;
import com.oazon.common.Logger;
import com.oazon.common.Settings;
import com.oazon.common.TaskHelper;
import com.oazon.common.TaskHelper.Task;
import com.oazon.common.TaskHelper.UITask;
import com.oazon.moco.bean.McServiceMsg;
import com.oazon.moco.bean.Metadata;
import com.oazon.moco.bean.ProviderAdapt;
import com.oazon.moco.lan.core.http.bean.TransportState;
import com.oazon.moco.lan.util.LanServer;
import com.oazon.moco.lan.util.UrlDecode;
import com.oazon.moco.link.core.LinkEventController;
import com.oazon.moco.link.core.LinkSDK;
import com.oazon.moco.link.core.source.LinkEventSource;
import com.oazon.moco.link.event.LanStatus;
import com.oazon.moco.playlist.PlayListManage;
import com.oazon.moco.playlist.bean.AbstractMedia;
import com.oazon.moco.playlist.bean.MediaMetadata;
import com.oazon.moco.playlist.bean.PlayListCurrentMode;
import com.oazon.moco.playlist.db.PlaylistDao;
import com.oazon.moco.playlist.db.ServiceMsgDao;
import com.oazon.moco.serialport.SerialSend;
import com.oazon.moco.serialport.core.EQFile;
import com.oazon.moco.serialport.core.Pack;
import com.oazon.common.util.Config;
import com.oazon.sonos.bean.GetMetadata;
import com.oazon.sonos.bean.GetMetadataResponse;
import com.oazon.sonos.core.ISonosSoap;
import com.oazon.sonos.core.SonosControler;
import com.oazon.sonos.listener.SonosListener;
import com.oazon.common.util.Utils;
import com.oazon.common.util.curcity.ActivityUtil;

/**
 * 主活动
 * 
 * Default launcher application.
 */
public class MainActivity extends BaseFragmentActivity implements
		OnMusicCategorySelectedListener, OnStorySelectedListener,
		FragmentChangeListener, VoicePlayListener {
	private static final String TAG = "MainActivity";

	private static final int PLAY_FRAGMENT_INDEX = 1;
	private static final int MSG_SHOW_PLAYFRAGMENT = 0;
	private int ACTIVITY_RESULT_FOR_WIFISETTING = 12;
	public MainFlagmentAdapter mFlagmentAdapter = null;
	private ViewPager mViewPager = null;
	private LauncherApplication mApp = null;
	private VolumeReceive mVolumeRecevie = null;
	private FrameLayout mLayoutMain = null;
	private DrawView mDrawView = null;
	private DisplayMetrics mDisplayMetrics = null;
	private float x = 0, y = 0;
	private PlayFragment playFrag;
	private static MainActivity instance;
	private int FIRST_TIME_START_WIFI = 0x146;

	// private LightnessControl lightNessControl;//disable 06.27

	public static MainActivity getInstance() {
		return instance;
	}

	public PlayFragment getPlayFrag() {
		return playFrag;
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_SHOW_PLAYFRAGMENT:
				setCurrentFocusFragment(MainActivity.PLAY_FRAGMENT_INDEX);
				break;
			default:
				break;
			}
		}
	};

	@SuppressLint("SimpleDateFormat")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.main_layout);
		LightnessControl.stopAutoBrightness(this);
		LightnessControl.SetLightness(this, 255);
		// lightNessControl = new LightnesControl();//disable 06.27
		// lightNessControl.SetLightness(this, 255);//disable 06.27

		mLayoutMain = (FrameLayout) findViewById(R.id.main_layout);
		LinkManager.getInstance().getHardWareVersion();
		PlayListManage.getInstance();
		mDisplayMetrics = getResources().getDisplayMetrics();
		Logger.d(TAG, "WIDTH= " + mDisplayMetrics.widthPixels + "Height="
				+ mDisplayMetrics.heightPixels);

		String lastPlayMode = Settings.getInstance(this).get(
				PlayListManage.PLAY_MODE);
		restorePlaymode(lastPlayMode);
		initViewPager();
		initFragment();
		MocoPlayerClient.getInstance().bindPlayService();
		((PlayFragment) mFlagmentAdapter.get(PLAY_FRAGMENT_INDEX))
				.setCurrentItem();

		mApp = ((LauncherApplication) getApplication());
		mApp.registerActivty(this);
		// 解决开机语音识别崩溃的问题,故屏蔽
		// startWifiSetting();

		mVolumeRecevie = new VolumeReceive();
		IntentFilter filter = new IntentFilter();
		filter.addAction("cozon.moco");
		registerReceiver(mVolumeRecevie, filter);

		mDrawView = new DrawView(MainActivity.this);
		mLayoutMain.addView(mDrawView);

		SerialSend.getInstance().sendStatus(SerialSend.Serial_OPEN);
		SerialSend.getInstance().sendStatus(SerialSend.Serial_HARDWAREVERSION);

		// 初始化音效
		// SerialSend.getInstance().sendEQFile(EQFile.EQ1_h, EQFile.EQ1_l);

		// 如果更新为真的就启动定时器,每天早上4:30
		// TODO:这部分需要重构@danny

		// configAutoUpdate();

		Settings.getInstance(this).setLong("boot_time",
				System.currentTimeMillis());
		// 这是光感自动调节
		// LightnessControl.startAutoBrightness(this);
		instance = this;

		if (Utils.isWifiConnected(this)
				&& lastPlayMode.equals(PlayListManage.PLAY_MODE_QUEUE)) {
			fillPlaylist();
		}
	}

	private void configAutoUpdate() {
		if ("true"
				.equals(Settings.getInstance(MainActivity.this).get("update"))) {
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.HOUR_OF_DAY, 4);
			cal.set(Calendar.SECOND, 0);
			cal.set(Calendar.MINUTE, 30);
			cal.set(Calendar.MILLISECOND, 0);

			Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
			intent.setAction("com.moco.autoupdate");

			PendingIntent sender = PendingIntent.getBroadcast(
					MainActivity.this, 0, intent, 0);
			AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
			alarm.set(AlarmManager.RTC, cal.getTimeInMillis(), sender);
		}
	}

	private void restorePlaymode(String mode) {
		if (mode.equals(PlayListManage.PLAY_MODE_QUEUE)) {
			Logger.d(TAG, "restore to PLAY_MODE_QUEUE");
			PlayListManage.getInstance().toQueue();
		} else if (mode.equals(PlayListManage.PLAY_MODE_RADIO)) {
			Logger.d(TAG, "restore to PLAY_MODE_RADIO");
			PlayListManage.getInstance().toSmartRadio(null);
		}

	}

	private void fillPlaylist() {
		PlayListManage.getInstance().addAll(
				new PlaylistDao(MainActivity.this).getAll());
		int index = MainActivity.this.getSharedPreferences("setting", 0)
				.getInt("postion", -1);
		Logger.d("wowdd1", "old index " + index);
		playFrag.playItem(index);
	}

	private void saveCurrentPlayPostion(int index) {
		SharedPreferences sp = this.getSharedPreferences("setting", 0);
		SharedPreferences.Editor editor = sp.edit();
		editor.putInt("postion", index);
		Logger.d("wowdd1", "position " + index);
		editor.commit();
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		if (FIRST_TIME_START_WIFI == 0x146) {
			showPlayFragment();
			FIRST_TIME_START_WIFI = 0x55;
			Logger.i(TAG, "FIRST_TIME_START_WIFI==0x146");
		}
		super.onActivityResult(arg0, arg1, arg2);
	}

	private void startWifiSetting() {

		if (!Utils.isWifiConnectedOrConnecting(this)) {

			startWifiSettingView();
			// startActivity(intent);
		}
	}

	/** 点击处特效动画 */
	private void showAnimation(float x, float y) {
		mDrawView.currentX = x;
		// y=dm.heightPixels-y-320;
		y = y - (mDisplayMetrics.heightPixels - mViewPager.getHeight())
				- mDrawView.circle / 2;
		// Logger.d("WGZ", x + " 重绘 " + y);
		mDrawView.currentY = y;
		// 重绘
		mDrawView.showAnim();
	}

	// 返回true表明算是方法已经处理该事件
	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		mApp.resetStartTime();

		if (intent == null)
			return;

		String action = intent.getStringExtra("action");
		if (!StringUtils.isEmpty(action)) {
			if (action.equals("play")) {

				/*
				 * PlayFragment pf = (PlayFragment) mFlagmentAdapter
				 * .getItem(PLAY_FRAGMENT_INDEX);
				 */

				setCurrentFocusFragment(PLAY_FRAGMENT_INDEX);
				playFrag.showPlayState();
				MocoPlayerClient.getInstance().iStart(false);
				playFrag.setsongLoadProgressDis();
				return;
			}
		}

		String playState = intent.getStringExtra("playState");
		if (TransportState.PAUSED_PLAYBACK.toString().equals(playState)) {
			PlayFragment pf = (PlayFragment) mFlagmentAdapter
					.getItem(PLAY_FRAGMENT_INDEX);
			pf.showPauseState();
			return;
		}
		String runningActivity = intent.getStringExtra("activity");

		if (!"MainActivity".equals(runningActivity)) {
			goActWhenStopProtectScr(runningActivity);
		}
		setIntent(intent);

		if ("VoiceFragment".equals(intent.getStringExtra("fragment_type"))) {
			processExtraData();
		}

	}

	// 对接语音识别返回的结果
	private void processExtraData() {// gavin
		try {
			Intent intent = this.getIntent();
			ArrayList<Metadata> items = intent
					.getParcelableArrayListExtra("voice_result");
			if (items == null) {
				return;
			}
			PlayListManage.getInstance().toQueue();
			onMusicListSelected(items);
		} catch (Exception e) {
		}
	}

	private void initViewPager() {
		mFlagmentAdapter = new MainFlagmentAdapter(this,
				getSupportFragmentManager());
		mViewPager = (ViewPager) this.findViewById(R.id.main_pager);
		mViewPager.setOffscreenPageLimit(5);
		mViewPager.setAdapter(mFlagmentAdapter);

		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				if (mFlagmentAdapter.getItem(position) instanceof MusicCategoryFragment)
					((MusicCategoryFragment) mFlagmentAdapter.getItem(position))
							.refreshRootPage(false);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

	}

	/**
	 * 初始化Fragment
	 */
	private void initFragment() {
		mFlagmentAdapter.clear();
		SettingFragment tempFragment = new SettingFragment();
		tempFragment.registerCallback(this);
		mFlagmentAdapter.append(tempFragment);
		playFrag = new PlayFragment(this);
		playFrag.registerCallback(this);
		playFrag.registerDefaultPlay(this);
		playFrag.registerPlayCb(new PlayCallback() {
			@Override
			public void playNext() {
				MocoPlayerClient.getInstance().playNext();
				LinkManager.getInstance().next();
			}

			@Override
			public void playPrev() {
				MocoPlayerClient.getInstance().playPrev();
				LinkManager.getInstance().previous();
			}

			@Override
			public void getCurrentList() {
			}

			@Override
			public void playNextAndDeleteCurrent() {
				// TODO some playNextAndDeleteCurrent 目前没有这个功能
			}

			@Override
			public void playItem(MusicItemInfo info) {
				MocoPlayerClient.getInstance().register(mStatusChangeCb);
				MocoPlayerClient.getInstance().playItem(info);
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						Logger.d("wowdd1", "playItem");
						if (PlayListManage.getInstance().getSaveCurrentMode() == PlayListCurrentMode.QUEUE) {
							saveCurrentPlayPostion(PlayListManage.getInstance()
									.getReadIndex());
						} else {
							PlayListManage.getInstance().update();
							PlayListManage.getInstance().dumpPlaylist();
						}
					}

				});
			}
		});
		mFlagmentAdapter.append(playFrag);

		MusicCategoryFragment musicFrag = new MusicCategoryFragment(null);
		musicFrag.registerCallback(this);
		mFlagmentAdapter.append(musicFrag);
		appendMusicFragment();

		setCurrentFocusFragment(PLAY_FRAGMENT_INDEX);
	}

	public void appendMusicFragment() {
		List<McServiceMsg> msgs = ServiceMsgDao.getInstance(this).getAll();
		if (msgs != null) {
			for (McServiceMsg mcServiceMsg : msgs) {
				MusicCategoryFragment musicFragment = new MusicCategoryFragment(
						mcServiceMsg);

				musicFragment.registerCallback(this);
				mFlagmentAdapter.append(musicFragment);
			}
		}
	}

	private void setCurrentFocusFragment(int index) {
		mViewPager.setCurrentItem(index, false);
	}

	public void setFocus2PlayFragment() {
		setCurrentFocusFragment(MainActivity.PLAY_FRAGMENT_INDEX);
	}

	@Override
	public void onStop() {
		super.onStop();
		PlayListManage.getInstance().syncDb();
	}

	@Override
	public void onDestroy() {
		PlayListManage.getInstance().stopAutoLoadImage();
		MocoPlayerClient.getInstance().unbindService();
		unregisterReceiver(mVolumeRecevie);
		super.onDestroy();
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		/*
		 * 当点击事件发生时，重绘小红点
		 */
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			y = event.getY();
			x = event.getX();
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			if (Math.abs(event.getX() - x) < 20
					&& Math.abs(event.getY() - y) < 20) {
				showAnimation(event.getX(), event.getY());
			}
		}

		mApp.resetStartTime();
		return super.dispatchTouchEvent(event);
	}

	boolean mIsSwitch = false;

	public void switchEnable() {
		mIsSwitch = true;
	}

	public void switchDisable() {
		mIsSwitch = false;
	}

	OnStatusChangeCallback mStatusChangeCb = new OnStatusChangeCallback.Stub() {

		@Override
		public void onStop(String id) throws RemoteException {
			Logger.d(TAG, "onStop.... = " + id);

			int index = mViewPager.getCurrentItem();

			if (index == PLAY_FRAGMENT_INDEX) {
				PlayFragment pf = (PlayFragment) mFlagmentAdapter
						.getItem(PLAY_FRAGMENT_INDEX);

				pf.showStopStateUI();
			}
		}

		@Override
		public void onPlaying() throws RemoteException {
			PlayFragment pf = (PlayFragment) mFlagmentAdapter
					.getItem(PLAY_FRAGMENT_INDEX);
			Metadata md = PlayListManage.getInstance().getCurrentMedia();
			if (md != null) {
				Logger.d("PlayListManager", "onplay=====" + md.getTitle()
						+ "===readindex=="
						+ PlayListManage.getInstance().getReadIndex());
			}
			LinkManager.getInstance().curSongInfo(md, pf.getCurMediaDuration());
			pf.requestSmartRadio();
			pf.setsongLoadProgressDis();
			exitPauseUI();
		}

		@Override
		public void onPause(String id) throws RemoteException {
			Logger.d(TAG, "onPause.... = " + id);
			int index = mViewPager.getCurrentItem();

			if (index == PLAY_FRAGMENT_INDEX) {
				PlayFragment pf = (PlayFragment) mFlagmentAdapter
						.getItem(PLAY_FRAGMENT_INDEX);
				pf.progressUpdateStop();
				LinkManager.getInstance().pause();
			}
		}

		@Override
		public void onError(final int nErrorCode) throws RemoteException {
			TaskHelper.UITask task = new UITask() {

				@Override
				public void callback(Exception e) {
					Logger.d(TAG, "onError.... = " + nErrorCode);

					if (Utils.isWifiConnectedOrConnecting(MainActivity.this)) {
						PlayFragment pf = (PlayFragment) mFlagmentAdapter
								.getItem(PLAY_FRAGMENT_INDEX);
						Toast.makeText(MainActivity.this, "歌曲解析失败",
								Toast.LENGTH_SHORT).show();
						PlayListManage.getInstance().remove(
								PlayListManage.getInstance().getCurrentIndex());
						if (PlayListManage.getInstance().getCurrentIndex() == 0) {
							if (PlayListManage.getInstance()
									.getSaveCurrentMode() == PlayListCurrentMode.SMART_RADIO) {
								onMusicRecommand();
								return;
							}
						}
						pf.playNext();
					} else {
						Toast.makeText(MainActivity.this, "WiFi未连接",
								Toast.LENGTH_SHORT).show();
					}
				}
			};
			TaskHelper.exec(task);
		}

		@Override
		public void onSeekComplete(String id) throws RemoteException {
			Logger.d(TAG, "onSeekComplete.... = " + id);
		}
		
		@Override
		public void playNext() throws RemoteException{
			playFrag.playNext();
		}

		@Override
		public void playPre() throws RemoteException {
			playFrag.playPre();
		}
	};

	public void exitPauseUI() {
		if (ActivityUtil.isForeground(this,
				"com.moco.launcher.activity.PopActivity")) {
			Intent intent = new Intent(this, PopActivity.class);
			intent.putExtra("fragment_type", "finish");
			this.startActivity(intent);
		}
	}

	// 添加歌曲到队列
	@Override
	public void addMusicList(int index, List<Metadata> metaDatas, boolean toPlay) {
		if (metaDatas == null)
			return;

		Logger.d("wowdd1", "addMusicList size:" + metaDatas.size());

		PlayFragment pf = (PlayFragment) mFlagmentAdapter
				.getItem(MainActivity.PLAY_FRAGMENT_INDEX);

		MocoPlayerClient.getInstance().register(mStatusChangeCb);
		Logger.d(TAG, "before clear" + PlayListManage.getInstance().size());
		Logger.d(TAG, "after clear" + PlayListManage.getInstance().size());

		if (pf.addPlayList(index, metaDatas) && toPlay) {
			Logger.d(TAG, "index" + index);
			pf.playItem(PlayListManage.getInstance().getReadIndex());
		} else {
			Logger.e(TAG, "PlayListSize:" + PlayListManage.getInstance().size()
					+ "==index" + index);
		}
	}

	public void addMusicList(List<Metadata> metaDatas) {
		if (metaDatas == null)
			return;

		Logger.d(TAG, "addMusicList size:" + metaDatas.size());
		PlayFragment pf = (PlayFragment) mFlagmentAdapter
				.getItem(MainActivity.PLAY_FRAGMENT_INDEX);

		MocoPlayerClient.getInstance().register(mStatusChangeCb);
		pf.addPlayList(metaDatas);
	}

	public void onServiceAdded(McServiceMsg msg, String uuid) {
		addProviderFragmentHan.removeMessages(1);
		Message message = addProviderFragmentHan.obtainMessage();
		message.obj = msg;
		message.what = 1;
		addProviderFragmentHan.sendMessageDelayed(message, 100);
	}

	Handler addProviderFragmentHan = new Handler() {
		public void handleMessage(Message msg) {
			addProviderFragment((McServiceMsg) msg.obj);
		};
	};

	private synchronized void addProviderFragment(final McServiceMsg msg) {

		ServiceMsgDao.getInstance(MainActivity.this).insertIntoServiceMsg(msg);
		LinkSDK.getInstance().notifyMCServices(LinkEventController.uiSource,
				ServiceMsgDao.getInstance(getBaseContext()).getAll(),
				msg.getUuid());
		for (int i = 0; i < mFlagmentAdapter.getCount(); i++) { // 判断是否已经有页面添加了

			Fragment fragment = mFlagmentAdapter.getItem(i);

			if (fragment == null
					|| !(fragment instanceof MusicCategoryFragment)) {
				continue;
			}
			MusicCategoryFragment itemFragment = (MusicCategoryFragment) fragment;

			String itemProv = itemFragment.getProvider();

			if (itemProv == null) {
				continue;
			}
			if (itemProv.equals(msg.getProvider())) {
				RequestManager.deleteByProvider(itemProv);
				itemFragment.refreshRootPage(true);
				return;
			}
		}
		SonosControler.getInstance(LauncherApplication.getInstance(), msg);
		MusicCategoryFragment fragment = new MusicCategoryFragment(msg);
		fragment.registerCallback(this);
		mFlagmentAdapter.append(fragment);
	}

	// 替换播放队列
	@Override
	public void onMusicListSelected(List<Metadata> metaDatas) {
		if (metaDatas == null)
			return;

		Logger.d(TAG, "onMusicListSelecte" + " size:" + metaDatas.size());
		MocoPlayerClient.getInstance().register(mStatusChangeCb);
		showPlayFragment();
		PlayFragment pf = (PlayFragment) mFlagmentAdapter
				.getItem(MainActivity.PLAY_FRAGMENT_INDEX);

		PlayListManage.getInstance().clearPlayList();
		pf.addPlayList(metaDatas);
		pf.playItem(0);
	}

	@Override
	public void onMusicListSelected(List<MediaMetadata> metaDatas,
			boolean recommand, String parentID, String sid) {
		if (metaDatas == null)
			return;

		Logger.d("wowdd1", "onMusicListSelecte size: " + metaDatas.size());
		for (int i = 0; i < metaDatas.size(); i++) {
			Logger.d("wowdd1", "-----------" + metaDatas.get(i).getTitle());
		}

		PlayFragment pf = (PlayFragment) mFlagmentAdapter
				.getItem(MainActivity.PLAY_FRAGMENT_INDEX);
		MocoPlayerClient.getInstance().register(mStatusChangeCb);
		showPlayFragment();
		List<Metadata> data = new ArrayList<Metadata>();
		for (int i = 0; i < metaDatas.size(); i++) {
			data.add(DataAdapter.dateAdapator(metaDatas.get(i), parentID, sid));
		}
		pf.addPlayList(PlayListManage.getInstance().getReadIndex() + 1, data);
		pf.playItem(PlayListManage.getInstance().getReadIndex() + 1);
	}

	public void showPlayFragment() {
		Message msg = mHandler.obtainMessage(MSG_SHOW_PLAYFRAGMENT);
		mHandler.sendMessage(msg);
	}

	@Override
	public void onMusicSelected(
			com.oazon.moco.playlist.bean.MediaMetadata item, String parentID,
			String sid) {
		if (item == null)
			return;

		Logger.d("wowdd1", "onMusicSelected title:" + item.getTitle()
				+ " getReadIndex:"
				+ PlayListManage.getInstance().getReadIndex());

		PlayFragment pf = (PlayFragment) mFlagmentAdapter
				.getItem(MainActivity.PLAY_FRAGMENT_INDEX);

		MocoPlayerClient.getInstance().register(mStatusChangeCb);
		showPlayFragment();

		int idx = 0;
		if (PlayListManage.getInstance().size() > 0){
			idx = PlayListManage.getInstance().getReadIndex() + 1;	
		}
		pf.addPlayItem(idx, DataAdapter.dateAdapator(item, parentID, sid));
	};

	// 故事类页面回调
	@Override
	public void onStoryReplay(MocoItemInfo item) {
	}

	// 故事类页面回调
	@Override
	public void onStoryContinue(MocoItemInfo item) {
	}

	@Override
	public void onMusicRecommand() {
		// 界面显示的时候，播放智能推荐的歌曲，
		String url = MOCO_CONSTANTS.RECOMMEND;
		PlayListManage.getInstance().toSmartRadio(null);

		int fetchSize = PlayListManage.getInstance().calFetchSize();
		Logger.d("wowdd1", "onMusicRecommand fetchSize:" + fetchSize);
		if (fetchSize <= 0) {
			Logger.d("wowdd1",
					"fetchSize <=0, do not nead request network resource");
			return;
		}
		url = url + "&count=" + fetchSize;

		final GetMetadata parameters = UrlDecode.parseUri(url);

		SonosControler.getInstance(this, null).getMetadata(mApp, parameters,
				new SonosListener() {

					@Override
					public void onResponse(Object response) {
						Logger.d(TAG, "onResponse");
						try {
							GetMetadataResponse<AbstractMedia> result = (GetMetadataResponse<AbstractMedia>) response;
							if (result == null)
								return;

							List<Metadata> metadatas = Collections.emptyList();
							metadatas = DataAdapter.paseMetadatas(result
									.getGetMetadataResult()
									.getMediaCollectionOrMediaMetadata(),
									parameters.getId(), parameters
											.getProvider());

							PlayListManage.getInstance().toSmartRadio(
									parameters);
							MainActivity.this.addMusicList(metadatas);
							playFrag.setProgressCount();
							if (PlayListManage.getInstance().getReadIndex() == -1) {
								playFrag.playItem(0);
							} else {
								playFrag.setCurrentItem();// once
							}
							PlayListManage.getInstance().dumpPlaylist();
						} catch (Exception e) {
							onError(0, e.getMessage());
						}
					}

					@Override
					public void onError(int err, String msg) {

					}
				});
	}

	// 显示右边的fragment，目前没有用到
	@Override
	public void nextFragment() {
		int n = this.mViewPager.getCurrentItem();
		n++;
		Logger.d(TAG, "N= " + n + "count= " + mFlagmentAdapter.getCount());

		if (n < mFlagmentAdapter.getCount())
			mViewPager.setCurrentItem(n);
	}

	// 显示左边的fragment，目前没有用到
	@Override
	public void prevFragment() {
		int n = this.mViewPager.getCurrentItem();
		n--;
		Logger.d(TAG, "N= " + n + "count= " + mFlagmentAdapter.getCount());
		if (n >= 0)
			mViewPager.setCurrentItem(n);
	}

	/**
	 * 语音识别结果添加到队列
	 */
	@Override
	public void onMusicListSelected(ArrayList<Metadata> musics) {
		PlayListManage.getInstance().toQueue();

		int idx = 0;
		if (PlayListManage.getInstance().size() > 0) {
			idx = PlayListManage.getInstance().getReadIndex() + 1;
		}
		addMusicList(idx, musics, true);
	}

	public void goActWhenStopProtectScr(String activityFlag) {
		if ("NewWifiSettingsActivity".equals(activityFlag)) {
			startActivity(NewWifiSettingsActivity.class);
		} else if ("ShutDownActivity".equals(activityFlag)) {
			startActivity(ShutDownActivity.class);
		} else if ("AboutActivity".equals(activityFlag)) {
			startActivity(AboutActivity.class);
		} else if ("GestureStatues".equals(activityFlag)) {
			startActivity(GestureStatues.class);
		} else if ("UpdateMsgActivity".equals(activityFlag)) {
			startActivity(UpdateMsgActivity.class);
		} else if ("showDownAppActivity".equals(activityFlag)) {
			startActivity(showDownAppActivity.class);
		}
	}

	public void startActivity(Class<?> Activity) {
		Intent intent = new Intent(MainActivity.this, Activity);
		startActivity(intent);
	}

	public void startWifiSettingView() {
		Intent intent = new Intent(this, NewWifiSettingsActivity.class);
		startActivityForResult(intent, ACTIVITY_RESULT_FOR_WIFISETTING);
	}

	public class VolumeReceive extends BroadcastReceiver {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			String name = arg1.getExtras().getString("Msg");
			Assert.notNEWS(name);

			Pack p = (Pack) arg1.getExtras().getSerializable("pack");
			Assert.notNull(p);

			if (name.equals("M_VOLUM_NUMBER")) {
				int number = Pack.readOne(p.getData());
				Settings.getInstance(MainActivity.this).set("volume",
						String.valueOf(number));
			}
		}
	}

	public void onServiceDelete(final String serviceName, final String uuid,
			final ChannelHandlerContext ctx) {
		TaskHelper.UITask task = new UITask() {
			@Override
			public void callback(Exception e) {
				String provider = "";
				// Fragment tempFragment = null;
				int index = -1;

				provider = ProviderAdapt.name2provider(serviceName);

				for (int i = 0; i < mFlagmentAdapter.getCount(); i++) {
					Fragment fragment = mFlagmentAdapter.getItem(i);
					if (fragment == null
							|| !(fragment instanceof MusicCategoryFragment)) {
						continue;
					}
					MusicCategoryFragment musciFragment = (MusicCategoryFragment) fragment;
					String mProvider = musciFragment.getProvider();

					if (mProvider == null) {

						continue;
					}
					if (mProvider.equals(provider)) {
						// tempFragment = musciFragment;
						Log.d("WWOW", "ssssssss==" + i);
						index = i;
						// mFlagmentAdapter.get
						// mFlagmentAdapter.remove(index);
						Log.e("", mFlagmentAdapter.getItemId(index) + "'");
					}
				}
				if (index < 0) {
					LanServer.responseResult(
							LanStatus.SERVICE_DELETE.toString(), -1, null, ctx);
				}
				mFlagmentAdapter.remove(index);
				LanServer.responseResult(LanStatus.SERVICE_DELETE.toString(),
						0, null, ctx);
				// mViewPager.removeViewAt(index);
			}
		};
		TaskHelper.exec(task);
		RequestManager.deleteByProvider(ProviderAdapt
				.name2provider(serviceName));
		ServiceMsgDao.getInstance(this).deleteById(
				ProviderAdapt.name2id(serviceName));
		LinkSDK.getInstance().notifyMCServices(LinkEventController.uiSource,
				ServiceMsgDao.getInstance(this).getAll(), uuid);
	}
}
